﻿using System;
using Biz.EF.Platform.Kq;
using Hjt212Parser;
using System.Linq;
using Biz.Buffer;
using Biz.EF.Gateway.Monitor;
using log4net;


namespace Biz.Process
{
    /// <summary>
    /// 主要处理离线、在线
    /// </summary>
    public class ProcessorStatus
    {
        private static ILog log = LogManager.GetLogger(typeof(ProcessorStatus));
        /// <summary>
        /// 离线指令处理
        /// 注意：方法内已保存
        /// 是否不要保存以提高效率，让外部调用程序保存 
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process0000(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var login = StringHelper.SubSuffixString(mn, 8);
                if (string.IsNullOrEmpty(login)) return;
                var datatime = Parser.GetDateTimeByDataTimeThenQnThenNow(content);
                if (!string.IsNullOrEmpty(mn))
                {
                    var items = pCtx.T_Login.Where(t => t.Login_ID.Equals(mn));
                    foreach (var item in items)
                    {
                        item.F_Line = 2;
                        item.Time_Login = datatime.ToString("yyyy-MM-dd HH:mm:ss");
                        item.Time_Updata = datatime.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        /// <summary>
        /// 心跳指令处理
        /// 在线处理，其实除掉0000的任何指令都表示在线
        /// 注意：方法内已保存
        /// 是否不要保存以提高效率，让外部调用程序保存 
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process9999(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var login = StringHelper.SubSuffixString(mn, 8);
                if (string.IsNullOrEmpty(login)) return;
                var datatime = Parser.GetDateTimeByDataTimeThenQnThenNow(content);
                if (!string.IsNullOrEmpty(mn))
                {
                    var items = pCtx.T_Login.Where(t => t.Login_ID.Equals(mn));
                    foreach (var item in items)
                    {
                        item.F_Line = 1;
                        item.Time_Login = datatime.ToString("yyyy-MM-dd HH:mm:ss");
                        item.Time_Updata = datatime.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        /// <summary>
        /// 市电停电，先操作Envi_PS_Waste_Water_Flow表修改状态，然后修改S_Envi_Monitor_status对应记录
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process3081(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;
                T_transmittal_Exec_Result result = new T_transmittal_Exec_Result
                {
                    QN = Parser.GetStringByKey("QN", content),
                    ST = Parser.GetStringByKey("ST", content),
                    CN = Parser.GetStringByKey("CN", content),
                    MN = mn,
                    Flag = Parser.GetStringByKey("Flag", content),
                    SendValue = Parser.GetStringByKey("CP", content),
                    ReturnValue = null,
                    Flag_process = "0",
                    Reason = null,
                    OperateDate = DateTime.Now
                };
                pCtx.T_transmittal_Exec_Result.Add(result);
                pCtx.SaveChanges();
                var items = pCtx.Envi_PS_Waste_Water_Flow.Where(t => t.Let_Port_ID == port.ID).ToList();
                if (items.Count >= 1)
                {
                    foreach (var item in items)
                    {
                        item.Power_Flag = true;
                    }
                    pCtx.SaveChanges();
                }
                var status =
                    pCtx.S_Envi_Monitor_status.Where(t => t.TempType.Equals("市电停电"))
                    .Where(t => t.Pollution_Source_ID.Equals(port.Pollution_Source_Id + ""))
                    .Where(t => t.Let_Port_No == port.ID)
                        .OrderByDescending(t => t.ID)
                        .FirstOrDefault();
                if (status == null)
                {
                    status = new S_Envi_Monitor_status();
                    pCtx.S_Envi_Monitor_status.Add(status);
                }
                status.Let_Port_No = port.ID;
                status.Pollution_Source_ID = port.Pollution_Source_Id + "";
                status.TempType = "市电停电";
                status.flag = 1;
                status.dTime = DateTime.Now;
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        public static void Process3082(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;
                T_transmittal_Exec_Result result = new T_transmittal_Exec_Result
                {
                    QN = Parser.GetStringByKey("QN", content),
                    ST = Parser.GetStringByKey("ST", content),
                    CN = Parser.GetStringByKey("CN", content),
                    MN = mn,
                    Flag = Parser.GetStringByKey("Flag", content),
                    SendValue = Parser.GetStringByKey("CP", content),
                    ReturnValue = null,
                    Flag_process = "0",
                    Reason = null,
                    OperateDate = DateTime.Now
                };
                pCtx.T_transmittal_Exec_Result.Add(result);
                pCtx.SaveChanges();
                var items = pCtx.Envi_PS_Waste_Water_Flow.Where(t => t.Let_Port_ID == port.ID).ToList();
                if (items.Count >= 1)
                {
                    foreach (var item in items)
                    {
                        item.Power_Flag = false;
                    }
                    pCtx.SaveChanges();
                }
                var status =
                    pCtx.S_Envi_Monitor_status.Where(t => t.TempType.Equals("市电停电"))
                    .Where(t => t.Pollution_Source_ID.Equals(port.Pollution_Source_Id + ""))
                    .Where(t => t.Let_Port_No == port.ID)
                        .OrderByDescending(t => t.ID)
                        .FirstOrDefault();
                if (status == null)
                {
                    status = new S_Envi_Monitor_status();
                    pCtx.S_Envi_Monitor_status.Add(status);
                }
                status.Let_Port_No = port.ID;
                status.Pollution_Source_ID = port.Pollution_Source_Id + "";
                status.TempType = "市电停电";
                status.flag = 0;
                status.dTime = DateTime.Now;
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        public static void Process3083(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;
                T_transmittal_Exec_Result result = new T_transmittal_Exec_Result
                {
                    QN = Parser.GetStringByKey("QN", content),
                    ST = Parser.GetStringByKey("ST", content),
                    CN = Parser.GetStringByKey("CN", content),
                    MN = mn,
                    Flag = Parser.GetStringByKey("Flag", content),
                    SendValue = Parser.GetStringByKey("CP", content),
                    ReturnValue = null,
                    Flag_process = "0",
                    Reason = null,
                    OperateDate = DateTime.Now
                };
                pCtx.T_transmittal_Exec_Result.Add(result);
                pCtx.SaveChanges();
                var items = pCtx.Envi_PS_Waste_Water_Flow.Where(t => t.Let_Port_ID == port.ID).ToList();
                if (items.Count >= 1)
                {
                    foreach (var item in items)
                    {
                        item.Power_Flag = true;
                    }
                    pCtx.SaveChanges();
                }
                var status =
                    pCtx.S_Envi_Monitor_status.Where(t => t.TempType.Equals("电动阀供电故障"))
                    .Where(t => t.Pollution_Source_ID.Equals(port.Pollution_Source_Id + ""))
                    .Where(t => t.Let_Port_No == port.ID)
                        .OrderByDescending(t => t.ID)
                        .FirstOrDefault();
                if (status == null)
                {
                    status = new S_Envi_Monitor_status();
                    pCtx.S_Envi_Monitor_status.Add(status);
                }
                status.Let_Port_No = port.ID;
                status.Pollution_Source_ID = port.Pollution_Source_Id + "";
                status.TempType = "电动阀供电故障";
                status.flag = 1;
                status.dTime = DateTime.Now;
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        public static void Process3084(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;
                T_transmittal_Exec_Result result = new T_transmittal_Exec_Result
                {
                    QN = Parser.GetStringByKey("QN", content),
                    ST = Parser.GetStringByKey("ST", content),
                    CN = Parser.GetStringByKey("CN", content),
                    MN = mn,
                    Flag = Parser.GetStringByKey("Flag", content),
                    SendValue = Parser.GetStringByKey("CP", content),
                    ReturnValue = null,
                    Flag_process = "0",
                    Reason = null,
                    OperateDate = DateTime.Now
                };
                pCtx.T_transmittal_Exec_Result.Add(result);
                pCtx.SaveChanges();
                var items = pCtx.Envi_PS_Waste_Water_Flow.Where(t => t.Let_Port_ID == port.ID).ToList();
                if (items.Count >= 1)
                {
                    foreach (var item in items)
                    {
                        item.Power_Flag = false;
                    }
                    pCtx.SaveChanges();
                }
                var status =
                    pCtx.S_Envi_Monitor_status.Where(t => t.TempType.Equals("电动阀供电故障"))
                    .Where(t => t.Pollution_Source_ID.Equals(port.Pollution_Source_Id + ""))
                    .Where(t => t.Let_Port_No == port.ID)
                        .OrderByDescending(t => t.ID)
                        .FirstOrDefault();
                if (status == null)
                {
                    status = new S_Envi_Monitor_status();
                    pCtx.S_Envi_Monitor_status.Add(status);
                }
                status.Let_Port_No = port.ID;
                status.Pollution_Source_ID = port.Pollution_Source_Id + "";
                status.TempType = "电动阀供电故障";
                status.flag = 0;
                status.dTime = DateTime.Now;
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        public static void Process3092(PlatformYgContext pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                var port = CommonInformation.GetLetportByMn(mn);
                if (port == null) return;
                var charge = Parser.GetDecimalByKey("Charge", content);
                if (charge == null) return;
                var item = pCtx.Envi_PS_Let_Port_Recharge_Card.FirstOrDefault(t => t.Let_Port == port.ID + "");

                if (item != null)
                {
                    item.Water = item.Water + charge;
                    item.Total_Amount = item.Total_Amount + charge;
                    item.Remain_Amount = item.Remain_Amount + charge;

                    var price = pCtx.T_price.FirstOrDefault(t => t.Type.Equals("污水"));
                    var record = new Envi_PS_Let_Port_Recharge_Record
                    {
                        Card_ID = item.ID,
                        Recharge_Time = Parser.GetDateTimeByKey("DataTime", content),
                        Recharge_Amount = charge * (price == null ? (decimal)2.5 : (price.price ?? (decimal)2.5)),
                        Recharge_Water_Measure = charge,
                        Recharge_Water_Price = (price == null ? (decimal)2.5 : (price.price ?? (decimal)2.5)),
                        Recharge_Type = "IC卡充值",
                        Remark = "",
                        State_Flag = ""
                    };
                    pCtx.Envi_PS_Let_Port_Recharge_Record.Add(record);
                    pCtx.SaveChanges();

                }

            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

        }
        public static void Process3085(PlatformYgContext pCtx, string content)
        {
            var mn = Parser.GetStringByKey("MN", content);
            if (string.IsNullOrEmpty(mn)) return;
            var port = CommonInformation.GetLetportByMn(mn);
            if (port == null) return;
            var alarm = Parser.GetStringByKey("Alarm", content);
            var returnAlarm = "相序异常";
            switch (alarm)
            {
                case "1":
                    returnAlarm = "相序异常";
                    break;
                case "2":
                    returnAlarm = "相序恢复";
                    break;
                case "3":
                    returnAlarm = "AD异常";
                    break;
                case "4":
                    returnAlarm = "AD恢复";
                    break;
            }

            T_transmittal_Exec_Result result = new T_transmittal_Exec_Result
            {
                QN = Parser.GetStringByKey("QN", content),
                ST = Parser.GetStringByKey("ST", content),
                CN = Parser.GetStringByKey("MN", content),
                MN = mn,
                Flag = Parser.GetStringByKey("Flag", content),
                SendValue = Parser.GetStringByKey("CP", content),
                ReturnValue = returnAlarm,
                Flag_process = "0",
                Reason = null,
                OperateDate = DateTime.Now
            };
            pCtx.T_transmittal_Exec_Result.Add(result);
            pCtx.SaveChanges();
        }
        public static void Process3071(PlatformYgContext pCtx, string content)
        {
            var mn = Parser.GetStringByKey("MN", content);
            if (string.IsNullOrEmpty(mn)) return;
            var port = CommonInformation.GetLetportByMn(mn);
            if (port == null) return;
            var per = Parser.GetIntByKey("Per", content);
            var flow = pCtx.Envi_PS_Waste_Water_Flow.FirstOrDefault(t => t.Let_Port_ID == port.ID);
            if (flow != null)
            {
                flow.Valve_Open_State = per;
                flow.Alarm_Flag = per < 50;
            }
            var qn = Parser.GetStringByKey("QN", content);
            var st = Parser.GetStringByKey("ST", content);
            var cn = Parser.GetStringByKey("CN", content);
            var result = pCtx.T_transmittal_Exec_Result.Where(t => t.QN.Equals(qn))
                .Where(t => t.MN.Equals(mn)).Where(t => t.ST.Equals(st)).FirstOrDefault(t => t.CN.Equals(cn));
            if (result != null)
            {
                result.ReturnValue = per + "";
                if (per == null)
                {
                    result.ReturnValue = "无输入信号";
                }
            }
            var monitor = pCtx.Envi_Valve_Monitor.FirstOrDefault(t => t.Let_Port == port.ID);
            if (monitor == null)
            {
                monitor = new Envi_Valve_Monitor();
                pCtx.Envi_Valve_Monitor.Add(monitor);
            }
            if (port.Pollution_Source_Id != null)
            {
                monitor.Pollution_Source = port.Pollution_Source_Id.Value;
            }
            monitor.Let_Port = port.ID;
            monitor.Get_Time = DateTime.Now;
            monitor.Valve_State = per + "";

            var status =
                   pCtx.S_Envi_Monitor_status.Where(t => t.TempType.Equals("市电停电"))
                   .Where(t => t.Pollution_Source_ID.Equals(port.Pollution_Source_Id + ""))
                   .Where(t => t.Let_Port_No == port.ID)
                       .OrderByDescending(t => t.ID)
                       .FirstOrDefault();
            if (status == null)
            {
                status = new S_Envi_Monitor_status();
                pCtx.S_Envi_Monitor_status.Add(status);
            }
            status.Let_Port_No = port.ID;
            status.Pollution_Source_ID = port.Pollution_Source_Id + "";
            status.TempType = "市电停电";
            status.flag = per < 50 ? 1 : 0;
            status.dTime = DateTime.Now;
            pCtx.SaveChanges();
            status =
                   pCtx.S_Envi_Monitor_status.Where(t => t.TempType.Equals("电动阀供电故障"))
                   .Where(t => t.Pollution_Source_ID.Equals(port.Pollution_Source_Id + ""))
                   .Where(t => t.Let_Port_No == port.ID)
                       .OrderByDescending(t => t.ID)
                       .FirstOrDefault();
            if (status == null)
            {
                status = new S_Envi_Monitor_status();
                pCtx.S_Envi_Monitor_status.Add(status);
            }
            status.Let_Port_No = port.ID;
            status.Pollution_Source_ID = port.Pollution_Source_Id + "";
            status.TempType = "电动阀供电故障";
            status.flag = per < 50 ? 1 : 0;
            status.dTime = DateTime.Now;
            pCtx.SaveChanges();
            var alarmType = "阀门状态有变动" + per + "%";
            var gsm = pCtx.T_GSM_warn.Where(t => t.MN.Equals(mn)).OrderByDescending(t => t.txtDate).FirstOrDefault(t => t.alarmType.Contains(alarmType));

            if (gsm?.txtDate == null || gsm.txtDate.Value.AddHours(1) < DateTime.Now)
            {
                var persons = CommonInformation.GetReceiverInfoes();
                foreach (var person in persons)
                {
                    gsm = new T_GSM_warn
                    {
                        MN = mn,
                        Tel = person.Value,
                        txt = "企业" + port.PS_Company_Name + "阀门状态有变动，于" + Parser.GetDateTimeByDataTimeThenQnThenNow(content) + "上报阀门状态为" + per + "%",
                        Flag = "0",
                        Let_Port_Id = port.ID,
                        txtDate = DateTime.Now,
                        alarmType = alarmType,
                        ReceiverPersonName = person.Key,
                        Pollution_Source_Name = port.PS_Company_Name
                    };
                    pCtx.T_GSM_warn.Add(gsm);
                }
                pCtx.SaveChanges();
            }


        }
        public static void Process1011(PlatformYgContext pCtx, string content)
        {
            var mn = Parser.GetStringByKey("MN", content);
            if (string.IsNullOrEmpty(mn)) return;

            var qn = Parser.GetStringByKey("QN", content);
            var st = Parser.GetStringByKey("ST", content);
            var cn = Parser.GetStringByKey("CN", content);
            var result = pCtx.T_transmittal_Exec_Result.Where(t => t.QN.Equals(qn))
                .Where(t => t.MN.Equals(mn)).Where(t => t.ST.Equals(st)).FirstOrDefault(t => t.CN.Equals(cn));
            if (result != null)
            {
                result.ReturnValue = Parser.GetStringByKey("SystemTime", content);
            }
            pCtx.SaveChanges();
        }
        public static void Process3098(PlatformYgContext pCtx, string content)
        {
            var mn = Parser.GetStringByKey("MN", content);
            if (string.IsNullOrEmpty(mn)) return;
            var now = DateTime.Now.AddSeconds(5);
            var resultStr = "QN=" + now.ToString("yyyyMMddHHmmssfff") + ";ST=32;CN=1012;PW=123456" + ";MN=" + mn
                                         + ";Flag=0;CP=&&SystemTime=" + now.ToString("yyyyMMddHHmmss") + "&&";
            resultStr = Crc.WrapByCrc(resultStr,"total");
            using (var gCtx = new GatewayMonitorContext())
            {
                send_ctr_cmd cmd = new send_ctr_cmd
                {
                    cn = "1012",
                    mn = mn,
                    qn = now.ToString("yyyyMMddHHmmssfff"),
                    is_sent = false,
                    send_string = resultStr,
                    sent_time = now,
                    send_time = now
                };
                gCtx.send_ctr_cmd.Add(cmd);
                gCtx.SaveChanges();
            }
            T_transmittal_Exec_Result result = new T_transmittal_Exec_Result
            {
                QN = Parser.GetStringByKey("QN", content),
                ST = Parser.GetStringByKey("ST", content),
                CN = "1012",
                MN = mn,
                Flag = Parser.GetStringByKey("Flag", content),
                SendValue = Parser.GetStringByKey("CP", content),
                ReturnValue = "",
                Flag_process = "0",
                Reason = null,
                OperateDate = DateTime.Now
            };
            pCtx.T_transmittal_Exec_Result.Add(result);
            pCtx.SaveChanges();
        }

    }
}
